package com.ve.s2g.util

import okhttp3.Credentials
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.util.concurrent.TimeUnit


object HttpClientManager {

    private val mOkHttpClient by lazy {
        OkHttpClient()
            .newBuilder()
            .connectTimeout(1000, TimeUnit.MILLISECONDS)
            .readTimeout(5000, TimeUnit.MILLISECONDS)
            .sslSocketFactory(SSLSocketClient.getSSLSocketFactory())
            .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
            .build()
    }

    //同步Get请求
    fun getSync(url: String): Response {
        val request = Request.Builder()
            .url(url)
            .build()
        val call = mOkHttpClient.newCall(request)
        return call.execute()
    }

    fun getSync(url: String, username: String, password: String): Response {
        val credential = Credentials.basic(username, password)
        val request = Request.Builder()
            .url(url)
            .addHeader("Authorization", credential)
            .build()
        val call = mOkHttpClient.newCall(request)
        return call.execute()
    }

    fun getSyncString(url: String): String {
        return getSync(url).body()!!.string()
    }


    fun getOkHttpClient(): OkHttpClient? {
        return mOkHttpClient
    }
}

fun main(args: Array<String>) {
    HttpClientManager.getSyncString("https://www.baidu.com/")
}